package com.macro.mall.tiny.controller;


import com.macro.mall.tiny.common.api.CommonPage;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.common.api.ResponseResult;
import com.macro.mall.tiny.domain.LoginUser;
import com.macro.mall.tiny.domain.User;
import com.macro.mall.tiny.dto.UmsAdminLoginParam;
import com.macro.mall.tiny.dto.umsAdminParam;
import com.macro.mall.tiny.dto.updatePasswordDTO;
import com.macro.mall.tiny.mbg.model.UmsAdmin;
import com.macro.mall.tiny.mbg.model.UmsRole;
import com.macro.mall.tiny.service.UmsAdminService;
import com.macro.mall.tiny.service.UmsRoleService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/admin")
public class UmsAdminController {

    @Autowired
    private UmsAdminService umsAdminService;
    @Autowired
    private UmsRoleService umsRoleService;
    @Value("Authorization")
    private String authorization;
    @Value("Bearer ")
    private String tokenHead;

    //用户注册
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public CommonResult<UmsAdmin> register(@Validated @RequestBody umsAdminParam umsAdminParam){
        log.info("用户注册:{}",umsAdminParam);

        UmsAdmin umsAdmin= umsAdminService.register(umsAdminParam);
        if(umsAdmin==null){
            return CommonResult.failed("用户名已存在");
        }
        return CommonResult.success(umsAdmin);
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ResponseResult login(@RequestBody UmsAdminLoginParam umsAdminLoginParam){
        log.info("用户登录：{}",umsAdminLoginParam);

        User user=new User();
        BeanUtils.copyProperties(umsAdminLoginParam,user);

        //登录
        return umsAdminService.login(user);
    }


    @PostMapping ("/logout")
    @ApiOperation("用户退出登录")
    public CommonResult logout(){
        log.info("用户退出登录");

        //退出登录
        return umsAdminService.logout();

    }

    //刷新token
    @GetMapping("/refreshToken")
    @ApiOperation("刷新token")
    public CommonResult refreshToken(HttpServletRequest request){
        log.info("刷新token");

        String token=request.getHeader(authorization);
        String refreshToken=umsAdminService.refreshToken(token);
        if(refreshToken==null){
            return CommonResult.failed("令牌已失效");
        }

        Map<String,String> map=new HashMap<>();
        map.put("token",refreshToken);
        map.put("tokenHead",tokenHead);

        return CommonResult.success(map);
    }

    //获取当前登录用户信息
    @GetMapping("/info")
    @ApiOperation("获取当前登录用户信息")
    @PreAuthorize("@ex.hasAuthority('/admin')")
    public CommonResult getAdminInfo(){
        log.info("获取当前登录用户信息");

        Authentication authenticationToken= SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser=(LoginUser) authenticationToken.getPrincipal();
        String username=loginUser.getXxuser().getUsername();

        //根据用户名查询回用户信息
        UmsAdmin umsAdmin=umsAdminService.selectByUsername(username);

        //创建返回数据类型
        Map<String,Object> map=new HashMap<>();
        map.put("username",umsAdmin.getUsername());
        map.put("icon",umsAdmin.getIcon());
        map.put("menus",umsRoleService.getMenuList(umsAdmin.getId()));

        //查询用户角色信息并封装返回
        List<UmsRole> roleList=umsRoleService.selectByUserId(umsAdmin.getId());
        List<String> rolesName=new ArrayList<>();
        for(UmsRole umsRole:roleList){
            String umsRoleName=umsRole.getName();
            rolesName.add(umsRoleName);
        }
        map.put("roles",rolesName);

        return CommonResult.success(map);
    }


    //根据用户名分页获取用户列表
    @GetMapping("/list")
    @ApiOperation("根据姓名分页获取用户列表")
    @PreAuthorize("@ex.hasAuthority('/admin')")
    public CommonResult<CommonPage<UmsAdmin>> getList(
            @RequestParam(value = "keyword",required=false)String userName,
            @RequestParam(value="pageNum",defaultValue="1")Integer pageNum,
            @RequestParam(value="pageSize",defaultValue="5")Integer pageSize){
        log.info("根据姓名分页获取用户列表：{}，{}，{}",userName,pageNum,pageSize);

        List<UmsAdmin> umsAdminList=umsAdminService.getList(userName,pageNum,pageSize);
        return CommonResult.success(CommonPage.restPage(umsAdminList));
    }

    //获取指定用户信息
    @GetMapping("/{id}")
    @ApiOperation("获取指定用户信息")
    @PreAuthorize("@ex.hasAuthority('/admin')")
    public CommonResult<UmsAdmin> getById(@PathVariable Long id){
        log.info("获取指定用户信息：{}",id);

        UmsAdmin umsAdmin=umsAdminService.getById(id);
        return CommonResult.success(umsAdmin);
    }

    //修改指定用户信息
    @PostMapping("/update/{id}")
    @ApiOperation("修改指定用户信息")
    @PreAuthorize("@ex.hasAuthority('/admin')")
    public CommonResult updateById(@PathVariable Long id,@RequestBody UmsAdmin umsAdmin){
        log.info("修改指定用户信息：{}，{}",id,umsAdmin);

        Integer code=umsAdminService.updateById(id,umsAdmin);
        return code==1?CommonResult.success(code):CommonResult.failed();
    }

    //修改指定用户密码
    @PostMapping("/updatePassword")
    @ApiOperation("修改指定用户密码")
    @PreAuthorize("@ex.hasAuthority('/admin')")
    public CommonResult updatePassword(@RequestBody updatePasswordDTO updatePasswordDTO){
        log.info("修改指定用户密码:{}",updatePasswordDTO);

        Integer code=umsAdminService.updatePassword(updatePasswordDTO);
        if(code==-1){
            return CommonResult.failed("提交参数不完整");
        }
        else if(code==-2){
            return CommonResult.failed("用户名不存在");
        }
        else if(code==-3){
            return CommonResult.failed("原密码错误");
        }
        else if(code==1){
            return CommonResult.success(code);
        }
        else{
            return CommonResult.failed();
        }

    }

    //删除指定用户信息
    @PostMapping("/delete/{id}")
    @ApiOperation("删除指定用户信息")
    @PreAuthorize("@ex.hasAuthority('/admin')")
    public CommonResult deleteById(@PathVariable Long id){
        log.info("删除指定用户信息:{}",id);

        Integer code=umsAdminService.deleteById(id);
        return code==1? CommonResult.success():CommonResult.failed();
    }

    //修改账号状态
    @PostMapping("/updateStatus/{id}")
    @ApiOperation("修改账号状态")
    @PreAuthorize("@ex.hasAuthority('/admin')")
    public CommonResult updateStatus(@PathVariable Long id,@RequestParam(value="status",required = true)Integer status){
        log.info("修改账号状态：{}，{}",id,status);

        UmsAdmin umsAdmin=new UmsAdmin();
        umsAdmin.setStatus(status);
        Integer code=umsAdminService.updateById(id,umsAdmin);
        return code==1? CommonResult.success(code):CommonResult.failed();
    }

    //给用户分配角色
    @PostMapping("/role/update")
    @ApiOperation("给用户分配角色")
    @PreAuthorize("@ex.hasAuthority('/admin')")
    public CommonResult updateRole(@RequestParam(value="adminId")Long userId,
                                   @RequestParam(value="roleIds")List<Long> roleIds){
        log.info("给用户分配角色：{}，{}",userId,roleIds);

        Integer code=umsAdminService.updateRole(userId,roleIds);
        return code>0? CommonResult.success():CommonResult.failed();
    }

    //获取指定用户角色
    @GetMapping("/role/{adminId}")
    @ApiOperation("获取指定用户角色")
    @PreAuthorize("@ex.hasAuthority('/admin')")
    public CommonResult<List<UmsRole>> getRoleByAdminId(@RequestParam(value="adminId") Long userId){
        log.info("获取指定用户角色:{}",userId);

        List<UmsRole> umsRoleList=umsAdminService.getRoleByAdminId(userId);
        return CommonResult.success(umsRoleList);
    }


}
